﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MvcEngine.Blog.Repositories;
using MvcEngine.Blog.Models.Entities;
using MvcEngine.LinqToSqlProvider;
using MvcEngine.Core;
using MvcEngine.Core.Helpers;
using MvcEngine.Core.Base;
using MvcEngine.Core.Utils;
using MvcEngine.Core.Content;

namespace MvcEngine.Blog.LinqToSqlProvider
{
    public class BlogRepository : Repository, IBlogRepository
    {
        public BlogData GetByPage(Guid pageId)
        {
            using (var contextManager = CreateContextManager(true))
            {
                return contextManager.Context.Blogs().SingleOrDefault(t => t.PageId == pageId);
            }
        }

        public BlogData Get(Guid blogId)
        {
            using (var contextManager = CreateContextManager(true))
            {
                return contextManager.Context.Blogs().SingleOrDefault(t => t.Id == blogId);
            }
        }

        public BlogData Get(string blogName)
        {
            using (var contextManager = CreateContextManager(true))
            {
                return contextManager.Context.Blogs().SingleOrDefault(t => t.Name == blogName);
            }
        }

        public void Update(BlogData blog)
        {
            using (var contextManager = CreateContextManager(false))
            {
                contextManager.Commit();
            }
        }

        public void Add(BlogData blog)
        {
            using (var contextManager = CreateContextManager(false))
            {
                contextManager.Context.Blogs().InsertOnSubmit(blog);
                contextManager.Commit();
            }
        }

        public IList<BlogData> GetAll(Guid siteId)
        {
            using (var contextManager = CreateContextManager(true))
            {
                return (from b in contextManager.Context.Blogs()
                        join
                        p in contextManager.Context.Pages() on b.PageId equals p.Id
                        where p.SiteId == siteId
                        select b).ToList();
            }
        }
    }
}
